import dayjs from "dayjs";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw } from "vue";
import { GridifyQueryBuilder, ConditionalOperator as op } from "gridify-client";
import { queryAuditTrails } from "@/swagger/api/auditTrail";


export function useRole(tableRef: Ref) {
  const form = reactive({
    operator: "",
    entity: "",
    operation: "",
    dateTime: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand",
      width: 50,
    },
    {
      label: "序号",
      prop: "id",
      formatter: ({ id }) => {
        const str = String(id || '');
        return str.length <= 13 ? str : str.slice(-12);
      }
    },
    {
      label: "操作人员",
      prop: "username",
      minWidth: 100
    },
    {
      label: "操作",
      prop: "operation",
      minWidth: 140
    },
    {
      label: "操作实体",
      prop: "entity",
      minWidth: 140
    },
    {
      label: "操作时间",
      prop: "dateTime",
      minWidth: 180,
      formatter: ({ dateTime }) =>
        dayjs(dateTime).format("YYYY-MM-DD HH:mm:ss")
    }
  ];

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
    onSearch();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  async function onSearch() {
    loading.value = true;
    const query = new GridifyQueryBuilder()
      .setPage(pagination.currentPage)
      .setPageSize(pagination.pageSize)
      .addOrderBy("dateTime", true)
      .addCondition("entity", op.Contains, form.entity);

    if (form.operator) {
      query.and().addCondition("username", op.Contains, form.operator);
    }

    if (form.operation) {
      query.and().addCondition("operation", op.Equal, form.operation);
    }

    if (form.dateTime) {
      const start = (new Date(form.dateTime[0])).toLocaleString();
      const end = (new Date(form.dateTime[1])).toLocaleString();
      query.and().addCondition("dateTime", op.GreaterThanOrEqual, start);
      query.and().addCondition("dateTime", op.LessThanOrEqual, end);
    }

    const queryBuilder = query.build() as any;
    const { data } = await queryAuditTrails(queryBuilder) as any;

    dataList.value = data.items;
    pagination.total = data.totalItems;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    resetForm,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
